package keter.framework.web.server;

import java.io.File;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.webapp.Configuration;
import org.eclipse.jetty.webapp.WebAppClassLoader;
import org.eclipse.jetty.webapp.WebAppContext;

import com.google.common.collect.Lists;

public class JettyFactory {    
        /**
         * 创建用于开发运行调试的Jetty Server, 以src/main/webapp为Web应用目录.
         */
        public static Server createServerInSource(int port, String contextPath, String webAppPath) {
            Server server = new Server();
           
            // 设置在JVM退出时关闭Jetty的钩子。
            server.setStopAtShutdown(true);
    
            ServerConnector connector = new ServerConnector(server);
            connector.setPort(port);
            // 解决Windows下重复启动Jetty居然不报告端口冲突的问题.
            connector.setReuseAddress(false);
            server.setConnectors(new Connector[] { connector });
    
            WebAppContext webContext = new WebAppContext(webAppPath, contextPath);
            server.setHandler(webContext);
    
            return server;
        }
        
        public static Server createServerInWar(int port, String contextPath, String warPath) {
        	// Create the server
            Server server = new Server(port);

            // Enable parsing of jndi-related parts of web.xml and jetty-env.xml
            Configuration.ClassList classlist = Configuration.ClassList.setServerDefault(server);
            classlist.addAfter("org.eclipse.jetty.webapp.FragmentConfiguration",
                    "org.eclipse.jetty.plus.webapp.EnvConfiguration",
                    "org.eclipse.jetty.plus.webapp.PlusConfiguration");
            classlist.addBefore(
                    "org.eclipse.jetty.webapp.JettyWebXmlConfiguration",
                    "org.eclipse.jetty.annotations.AnnotationConfiguration");

            // Create a WebApp
            WebAppContext webapp = new WebAppContext();
            webapp.setContextPath(contextPath);
            File warFile = new File(warPath);
            webapp.setWar(warFile.getAbsolutePath());
            webapp.setAttribute(
                    "org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",
                    ".*/javax.servlet-[^/]*\\.jar$|.*/servlet-api-[^/]*\\.jar$");
            server.setHandler(webapp);
			return server;
        }
    
        /**
         * 设置除jstl-*.jar外其他含tld文件的jar包的名称.
         * jar名称不需要版本号，如sitemesh, shiro-web
         */
        public static void setTldJarNames(Server server, String... jarNames) {
            WebAppContext context = (WebAppContext) server.getHandler();
            List<String> jarNameExprssions = Lists.newArrayList(".*/jstl-[^/]*\\.jar$", ".*/.*taglibs[^/]*\\.jar$");
            for (String jarName : jarNames) {
                jarNameExprssions.add(".*/" + jarName + "-[^/]*\\.jar$");
            }
    
            context.setAttribute("org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",
                    StringUtils.join(jarNameExprssions, '|'));
    
        }
    
        /**
         * 快速重新启动application，重载target/classes与target/test-classes.
         */
        public static void reloadContext(Server server) throws Exception {
            WebAppContext context = (WebAppContext) server.getHandler();
    
            System.out.println("[INFO] Application reloading");
            context.stop();
    
            WebAppClassLoader classLoader = new WebAppClassLoader(context);
            classLoader.addClassPath("target/classes");
            classLoader.addClassPath("target/test-classes");
            context.setClassLoader(classLoader);
    
            context.start();
    
            System.out.println("[INFO] Application reloaded");
        }
    }